package com.way.filemanager.util;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.drawable.Drawable;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.util.DisplayMetrics;
import android.util.Log;

//import com.aliyun.ams.ta.StatConfig;
//import com.aliyun.ams.ta.TA;
import com.way.filemanager.FileManagerAppFrame;
import com.way.filemanager.R;
import com.way.filemanager.navigation.MyFileManager.FileOrder;
import com.way.filemanager.navigation.Utils.FileFT;
import com.way.filemanager.navigation.Utils.FileFTs;

import java.io.File;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Locale;
import java.util.Map;

@SuppressLint("SimpleDateFormat")
public class CommonFunc {
    private static final String TAG = "CommonFunc";
    public final static boolean bIsCloseUserTrack = false;
    private static final HashMap<String, Integer> sFileTypeMap = new HashMap<String, Integer>();
    static {
        sFileTypeMap.put("MP3", Integer.valueOf(CommonIdDef.CATEGORY_ITEM_ID_MUSIC));
        sFileTypeMap.put("MPGA", Integer.valueOf(CommonIdDef.CATEGORY_ITEM_ID_MUSIC));
        sFileTypeMap.put("APE", Integer.valueOf(CommonIdDef.CATEGORY_ITEM_ID_MUSIC));
        sFileTypeMap.put("M4A", Integer.valueOf(CommonIdDef.CATEGORY_ITEM_ID_MUSIC));
        sFileTypeMap.put("WAV", Integer.valueOf(CommonIdDef.CATEGORY_ITEM_ID_MUSIC));
        sFileTypeMap.put("AMR", Integer.valueOf(CommonIdDef.CATEGORY_ITEM_ID_MUSIC));
        sFileTypeMap.put("AWB", Integer.valueOf(CommonIdDef.CATEGORY_ITEM_ID_MUSIC));
        sFileTypeMap.put("DCF", Integer.valueOf(CommonIdDef.CATEGORY_ITEM_ID_MUSIC));
        sFileTypeMap.put("WMA", Integer.valueOf(CommonIdDef.CATEGORY_ITEM_ID_MUSIC));
        sFileTypeMap.put("OGG", Integer.valueOf(CommonIdDef.CATEGORY_ITEM_ID_MUSIC));
        sFileTypeMap.put("OGA", Integer.valueOf(CommonIdDef.CATEGORY_ITEM_ID_MUSIC));
        sFileTypeMap.put("AAC", Integer.valueOf(CommonIdDef.CATEGORY_ITEM_ID_MUSIC));
        sFileTypeMap.put("MKA", Integer.valueOf(CommonIdDef.CATEGORY_ITEM_ID_MUSIC));
        sFileTypeMap.put("MID", Integer.valueOf(CommonIdDef.CATEGORY_ITEM_ID_MUSIC));
        sFileTypeMap.put("MIDI", Integer.valueOf(CommonIdDef.CATEGORY_ITEM_ID_MUSIC));
        sFileTypeMap.put("SMF", Integer.valueOf(CommonIdDef.CATEGORY_ITEM_ID_MUSIC));
        sFileTypeMap.put("IMY", Integer.valueOf(CommonIdDef.CATEGORY_ITEM_ID_MUSIC));
        sFileTypeMap.put("RTX", Integer.valueOf(CommonIdDef.CATEGORY_ITEM_ID_MUSIC));
        sFileTypeMap.put("OTA", Integer.valueOf(CommonIdDef.CATEGORY_ITEM_ID_MUSIC));
        sFileTypeMap.put("MXMF", Integer.valueOf(CommonIdDef.CATEGORY_ITEM_ID_MUSIC));

        sFileTypeMap.put("MP2", Integer.valueOf(CommonIdDef.CATEGORY_ITEM_ID_VIDEO));
        sFileTypeMap.put("3GA", Integer.valueOf(CommonIdDef.CATEGORY_ITEM_ID_VIDEO));
        sFileTypeMap.put("MOV", Integer.valueOf(CommonIdDef.CATEGORY_ITEM_ID_VIDEO));
        sFileTypeMap.put("QT", Integer.valueOf(CommonIdDef.CATEGORY_ITEM_ID_VIDEO));
        sFileTypeMap.put("MPEG", Integer.valueOf(CommonIdDef.CATEGORY_ITEM_ID_VIDEO));
        sFileTypeMap.put("MPG", Integer.valueOf(CommonIdDef.CATEGORY_ITEM_ID_VIDEO));
        sFileTypeMap.put("MP4", Integer.valueOf(CommonIdDef.CATEGORY_ITEM_ID_VIDEO));
        sFileTypeMap.put("M4V", Integer.valueOf(CommonIdDef.CATEGORY_ITEM_ID_VIDEO));
        sFileTypeMap.put("3GP", Integer.valueOf(CommonIdDef.CATEGORY_ITEM_ID_VIDEO));
        sFileTypeMap.put("3GPP", Integer.valueOf(CommonIdDef.CATEGORY_ITEM_ID_VIDEO));
        sFileTypeMap.put("3G2", Integer.valueOf(CommonIdDef.CATEGORY_ITEM_ID_VIDEO));
        sFileTypeMap.put("3GPP2", Integer.valueOf(CommonIdDef.CATEGORY_ITEM_ID_VIDEO));
        sFileTypeMap.put("MKV", Integer.valueOf(CommonIdDef.CATEGORY_ITEM_ID_VIDEO));
        sFileTypeMap.put("WEBM", Integer.valueOf(CommonIdDef.CATEGORY_ITEM_ID_VIDEO));
        sFileTypeMap.put("TS", Integer.valueOf(CommonIdDef.CATEGORY_ITEM_ID_VIDEO));
        sFileTypeMap.put("MTS", Integer.valueOf(CommonIdDef.CATEGORY_ITEM_ID_VIDEO));
        sFileTypeMap.put("M2TS", Integer.valueOf(CommonIdDef.CATEGORY_ITEM_ID_VIDEO));
        sFileTypeMap.put("AVI", Integer.valueOf(CommonIdDef.CATEGORY_ITEM_ID_VIDEO));
        sFileTypeMap.put("FLV", Integer.valueOf(CommonIdDef.CATEGORY_ITEM_ID_VIDEO));
        sFileTypeMap.put("F4V", Integer.valueOf(CommonIdDef.CATEGORY_ITEM_ID_VIDEO));
        sFileTypeMap.put("PFV", Integer.valueOf(CommonIdDef.CATEGORY_ITEM_ID_VIDEO));
        sFileTypeMap.put("FLA", Integer.valueOf(CommonIdDef.CATEGORY_ITEM_ID_VIDEO));
        sFileTypeMap.put("WMV", Integer.valueOf(CommonIdDef.CATEGORY_ITEM_ID_VIDEO));
        sFileTypeMap.put("ASF", Integer.valueOf(CommonIdDef.CATEGORY_ITEM_ID_VIDEO));

        sFileTypeMap.put("JPG", Integer.valueOf(CommonIdDef.CATEGORY_ITEM_ID_PICTURE));
        sFileTypeMap.put("JPEG", Integer.valueOf(CommonIdDef.CATEGORY_ITEM_ID_PICTURE));
        sFileTypeMap.put("GIF", Integer.valueOf(CommonIdDef.CATEGORY_ITEM_ID_PICTURE));
        sFileTypeMap.put("PNG", Integer.valueOf(CommonIdDef.CATEGORY_ITEM_ID_PICTURE));
        sFileTypeMap.put("BMP", Integer.valueOf(CommonIdDef.CATEGORY_ITEM_ID_PICTURE));
        sFileTypeMap.put("WBMP", Integer.valueOf(CommonIdDef.CATEGORY_ITEM_ID_PICTURE));
        sFileTypeMap.put("WEBP", Integer.valueOf(CommonIdDef.CATEGORY_ITEM_ID_PICTURE));
        sFileTypeMap.put("MPO", Integer.valueOf(CommonIdDef.CATEGORY_ITEM_ID_PICTURE));


        sFileTypeMap.put("TXT", Integer.valueOf(CommonIdDef.CATEGORY_ITEM_ID_TEXT));
        sFileTypeMap.put("HTM", Integer.valueOf(CommonIdDef.CATEGORY_ITEM_ID_TEXT));
        sFileTypeMap.put("HTML", Integer.valueOf(CommonIdDef.CATEGORY_ITEM_ID_TEXT));
        sFileTypeMap.put("PDF", Integer.valueOf(CommonIdDef.CATEGORY_ITEM_ID_TEXT));
        sFileTypeMap.put("DOC", Integer.valueOf(CommonIdDef.CATEGORY_ITEM_ID_TEXT));
        sFileTypeMap.put("XLS", Integer.valueOf(CommonIdDef.CATEGORY_ITEM_ID_TEXT));
        sFileTypeMap.put("PPT", Integer.valueOf(CommonIdDef.CATEGORY_ITEM_ID_TEXT));
        sFileTypeMap.put("FLAC", Integer.valueOf(CommonIdDef.CATEGORY_ITEM_ID_MUSIC));
        sFileTypeMap.put("DOCX", Integer.valueOf(CommonIdDef.CATEGORY_ITEM_ID_TEXT));
        sFileTypeMap.put("DOTX", Integer.valueOf(CommonIdDef.CATEGORY_ITEM_ID_TEXT));
        sFileTypeMap.put("XLSX", Integer.valueOf(CommonIdDef.CATEGORY_ITEM_ID_TEXT));
        sFileTypeMap.put("XLTX", Integer.valueOf(CommonIdDef.CATEGORY_ITEM_ID_TEXT));
        sFileTypeMap.put("PPTX", Integer.valueOf(CommonIdDef.CATEGORY_ITEM_ID_TEXT));
        sFileTypeMap.put("POTX", Integer.valueOf(CommonIdDef.CATEGORY_ITEM_ID_TEXT));
        sFileTypeMap.put("PPSX", Integer.valueOf(CommonIdDef.CATEGORY_ITEM_ID_TEXT));

        sFileTypeMap.put("ZIP", Integer.valueOf(CommonIdDef.CATEGORY_ITEM_ID_ZIP));
        sFileTypeMap.put("RAR", Integer.valueOf(CommonIdDef.CATEGORY_ITEM_ID_ZIP));
        sFileTypeMap.put("APK", Integer.valueOf(CommonIdDef.CATEGORY_ITEM_ID_PACKAGE));

    }

    public static String CreateTimeFormat_second(long time) {
        SimpleDateFormat formatter = new
        SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(time);
        return formatter.format(cal.getTime());
    }
    public static String CreateTimeFormat(long time) {
        SimpleDateFormat formatter = new
        //SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat("yyyy-MM-dd HH:mm");
        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(time);
        return formatter.format(cal.getTime());
    }
    public static String FormetFileSize(long fileS) {
        if(fileS == 0)
        {
            return "0M";
        }
        DecimalFormat df = new DecimalFormat("#.00");
        String fileSizeString = "";
        if (fileS < 1024) {
            fileSizeString = df.format((double) fileS) + "B";
        } else if (fileS < 1048576) {
            fileSizeString = df.format((double) fileS / 1024) + "K";
        } else if (fileS < 1073741824) {
            fileSizeString = df.format((double) fileS / 1048576) + "M";
        } else {
            fileSizeString = df.format((double) fileS / 1073741824) + "G";
        }
        return fileSizeString;
    }
   public static void shareDialog(Context mActivity,FileInfo[] list) {

        ArrayList<Uri> uris = new ArrayList<Uri>();
        String mimeType = null;
        for (int i = 0; i < list.length; i++) {
            File file = new File(list[i].GetFullPath());
            mimeType = MimeTypeHelper.getMimeType(mActivity, file.getName());
            Uri u = Uri.fromFile(file);


            uris.add(u);
        }
        boolean multiple = uris.size() > 1;
        Intent intent = new Intent(multiple ? android.content.Intent.ACTION_SEND_MULTIPLE
                : android.content.Intent.ACTION_SEND);
        if (multiple) {
            intent.setType("*/*");
            intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);
        } else {
            intent.setType(mimeType);
            intent.putExtra(Intent.EXTRA_STREAM, uris.get(0));
        }
        //bug101912
        mActivity.startActivity(Intent.createChooser(intent, mActivity.getText(R.string.actions_title_Share)));
    }
   public static void shareDialog(Context mActivity,LinkedList<File> list) {

       ArrayList<Uri> uris = new ArrayList<Uri>();
       String mimeType = null;
       for (int i = 0; i < list.size(); i++) {
           File file = list.get(i);
           mimeType = MimeTypeHelper.getMimeType(mActivity, file.getName());
           Uri u = Uri.fromFile(file);


           uris.add(u);
       }
       boolean multiple = uris.size() > 1;
       Intent intent = new Intent(multiple ? android.content.Intent.ACTION_SEND_MULTIPLE
               : android.content.Intent.ACTION_SEND);
       if (multiple) {
           intent.setType("*/*");
           intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);
       } else {
           intent.setType(mimeType);
           intent.putExtra(Intent.EXTRA_STREAM, uris.get(0));
       }
       //bug101912
       mActivity.startActivity(Intent.createChooser(intent, mActivity.getText(R.string.actions_title_Share)));
   }

    public static Uri ParseAppUriRes(Context mActivity,int type,String ext) {
        Uri uri = null;
        switch (type)
        {
            case CommonIdDef.CATEGORY_ITEM_ID_PICTURE:
                uri = CommonFunc.getResourceUri(mActivity,R.drawable.ic_photo_normal);
                break;
            case CommonIdDef.CATEGORY_ITEM_ID_MUSIC:
                uri = CommonFunc.getResourceUri(mActivity,R.drawable.ic_music_normal);
                break;
            case CommonIdDef.CATEGORY_ITEM_ID_VIDEO:
                uri = CommonFunc.getResourceUri(mActivity,R.drawable.ic_video_normal);
                break;
            case CommonIdDef.CATEGORY_ITEM_ID_PACKAGE:
                uri = CommonFunc.getResourceUri(mActivity,R.drawable.ic_apk_normal);
                break;
            case CommonIdDef.CATEGORY_ITEM_ID_TEXT:
                int id = R.drawable.ic_txt_normal;
                if(ext.equalsIgnoreCase("doc"))
                    id = R.drawable.ic_doc_normal;
                else if(ext.equalsIgnoreCase("ppt"))
                    id = R.drawable.ic_ppt_normal;
                else if(ext.equalsIgnoreCase("xls"))
                    id = R.drawable.ic_xls_normal;
                else if(ext.equalsIgnoreCase("pdf"))
                    id = R.drawable.ic_pdf_normal;

                uri = CommonFunc.getResourceUri(mActivity,id);
                break;
            case CommonIdDef.CATEGORY_ITEM_ID_ZIP:
                uri = CommonFunc.getResourceUri(mActivity,R.drawable.ic_zip_normal);
                break;
            default:
                uri = CommonFunc.getResourceUri(mActivity,R.drawable.ic_unknown_normal);
                break;
        }

        return uri;
    }
    public static int getFileType(String path) {
        int lastDot = path.lastIndexOf(".");
        if (lastDot <= 0)
            return 0;
        //Log.v("crash", "path:"+path);
        String ext = path.substring(lastDot + 1).toUpperCase(Locale.US);
        //Log.v("crash", "sFileTypeMap:"+sFileTypeMap);
        if(sFileTypeMap.containsKey(ext))
            return sFileTypeMap.get(ext);
        else
            return 0;
    }

    public static Uri getResourceUri(Context context, int res) {
        try {
        Context packageContext = context.createPackageContext(context.getPackageName(),
                    Context.CONTEXT_RESTRICTED);
            Resources resources = packageContext.getResources();

            String appPkg = packageContext.getPackageName();
            String resPkg = resources.getResourcePackageName(res);
            String type = resources.getResourceTypeName(res);
            String name = resources.getResourceEntryName(res);


            Uri.Builder uriBuilder = new Uri.Builder();
            uriBuilder.scheme(ContentResolver.SCHEME_ANDROID_RESOURCE);
            uriBuilder.encodedAuthority(appPkg);
            uriBuilder.appendEncodedPath(type);
            if (!appPkg.equals(resPkg)) {
                uriBuilder.appendEncodedPath(resPkg + ":" + name);
            } else {
                uriBuilder.appendEncodedPath(name);
            }
            return uriBuilder.build();

        } catch (Exception e) {
            return null;
        }
    }


    public final static String OnClick_Copy = "OnClick_Copy";
    public final static String OnClick_Cut = "OnClick_Cut";
    public final static String OnClick_Delete = "OnClick_Delete";
    public final static String OnClick_Search = "OnClick_Search";
    public final static String OnClick_Sort = "OnClick_Sort";
    public final static String OnClick_Paste = "OnClick_Paste";
    public final static String OnClick_Share = "OnClick_Share";
    public final static String OnClick_New = "OnClick_New";
    public final static String OnClick_Hide = "OnClick_Hide";
    public final static String OnClick_Login = "OnClick_Login";
    public final static String OnClick_Download = "OnClick_Download";
    public final static String OnClick_Upload = "OnClick_Upload";
    public final static String OnClick_Unzip = "OnClick_Unzip";
    public final static String OnClick_Zip = "OnClick_Zip";
    public final static String OnClick_Delete_All = "OnClick_Delete_All";//
    public final static String OnClick_Sort_name = "OnClick_Sort_name";
    public final static String OnClick_Sort_size = "OnClick_Sort_size";
    public final static String OnClick_Sort_date = "OnClick_Sort_date";
    public final static String OnClick_Sort_type = "OnClick_Sort_type";
    public final static String OnClick_Refresh = "OnClick_Refresh";

    public final static String LongPress_Rename = "LongPress_Rename";
    public final static String LongPress_Detail = "LongPress_Detail";
    public final static String LongPress_Crush = "LongPress_Crush";
    public final static String LongPress_Copy = "LongPress_Copy";
    public final static String LongPress_Cut = "LongPress_Cut";
    public final static String LongPress_Delete = "LongPress_Delete";
    public final static String LongPress_Share = "LongPress_Share";
    public final static String LongPress_Zip = "LongPress_Zip";
    public static void TA_Click(String  Button) {
        if(bIsCloseUserTrack)
            return;
        //TA.getInstance().getDefaultTracker().ctrlClicked(FileManagerAppFrame.class,Button);
        //TA.getInstance().getDefaultTracker().commitEvent(PageString[LastPageId], 2101,Button, null, null, null);
    }


    public final static String Category_Image = "Category_Image";
    public final static String Category_Music = "Category_Music";
    public final static String Category_Video = "Category_Video";
    public final static String Category_Apk = "Category_Apk";
    public final static String Category_Text = "Category_Text";
    public final static String Category_Zip = "Category_Zip";
    public static void TA_EnterMode(String type) {
        if(bIsCloseUserTrack)
            return;
        //Map<String, String> lMap = new HashMap<String, String>();
        //lMap.put("CategoryType", type);
        //TA.getInstance().getDefaultTracker().commitEvent("CategoryEnter", lMap);
        //TA.getInstance().getDefaultTracker().ctrlClicked(FileManagerAppFrame.class,type);
        //TA.getInstance().getDefaultTracker().commitEvent(PageString[LastPageId], 2101,type, null, null, null);
    }

    static int LastPageId = 0;
    static long LastChargeTime = 0;
    final static String []PageString = {"Page_HomeShell","Page_CategoryBrowse","Page_AllFiles","Page_OnlineFiles"};
    final static String []ActionByString = {"Action_Fly","Action_ActionBar"};
    public static void TA_EnterPage(int PageTo,int by) {
        if(bIsCloseUserTrack)
            return;

        //Id 0:Page_HomeShell,
        //Id 1:Page_CategoryBrowse,
        //Id 2:Page_AllFiles,
        //Id 3:Page_OnlineFiles,
        //long Resident=0;
        //Map<String, String> lMap = new HashMap<String, String>();

        if((PageTo >= PageString.length)||(PageTo < 0))
            return;
        //TA.getInstance().getDefaultTracker().pageLeave(PageString[LastPageId]);
        //TA.getInstance().getDefaultTracker().pageEnter(PageString[PageTo]);
        LastPageId = PageTo;
        /*
        lMap.put("PageFrom", PageString[LastPageId]);
        lMap.put("PageTo", PageString[PageTo]);
        LastPageId = PageTo;
        if((by >= ActionByString.length)&&(by >= 0))
            lMap.put("ActionBy", ActionByString[by]);
        else
            lMap.put("ActionBy", ActionByString[0]);

        if(LastChargeTime > 0)
        {
            Resident = System.currentTimeMillis()-LastChargeTime;
            LastChargeTime = System.currentTimeMillis();
        }
        else
        {
            Resident = 0;
            LastChargeTime = System.currentTimeMillis();
        }
        lMap.put("Resident", String.valueOf(Resident));
        TA.getInstance().getDefaultTracker().commitEvent("PageEnter", lMap);*/
    }
    public static void TA_ActivityStart(Activity pActivity) {
        if(bIsCloseUserTrack)
            return;
        //TA.getInstance().getDefaultTracker().activityStart(pActivity);

    }
    public static void TA_ActivityStop(Activity pActivity) {
        if(bIsCloseUserTrack)
            return;
        //TA.getInstance().getDefaultTracker().activityStop(pActivity);

    }
    public static void TA_AppOncreate(Context pActivity) {
        if(bIsCloseUserTrack)
            return;
        //StatConfig.getInstance().setContext(pActivity);

        //com.aliyun.ams.ta.Tracker lTracker = TA.getInstance().getTracker("21736480");
        //TA.getInstance().setDefaultTracker(lTracker);

    }

    public static final int NAME_INDEX = 0;
    public static final int SIZE_INDEX = 1;
    public static final int DATE_INDEX = 2;
    public static final int TYPE_INDEX = 3;

    public static int fileOrder2Index(FileOrder fo)
    {
        switch(fo)
        {
            default: case name: return NAME_INDEX;
            case size: return SIZE_INDEX;
            case date: return DATE_INDEX;
            case type: return TYPE_INDEX;
        }
    }
    public static FileOrder index2FileOrder(int index)
    {
        switch(index)
        {
            default: case NAME_INDEX: return FileOrder.name;
            case SIZE_INDEX: return FileOrder.size;
            case DATE_INDEX: return FileOrder.date;
            case TYPE_INDEX: return FileOrder.type;
        }
    }

    private final static String DEFAULT_FILE_ORDER_STRING = FileOrder.name.toString();
    public static FileOrder loadSaved(Context mActivity)
    {
        SharedPreferences sp = mActivity.getSharedPreferences(CommonIdDef.SAVE_KEY_PREFERENCE, Context.MODE_PRIVATE);
        FileOrder mOrder = FileOrder.valueOf(sp.getString(CommonIdDef.SAVE_KEY_ORDER, DEFAULT_FILE_ORDER_STRING));
        return mOrder;
    }
    public static void saveOrder(Context mActivity,FileOrder o)
    {
        SharedPreferences sp = mActivity.getSharedPreferences(CommonIdDef.SAVE_KEY_PREFERENCE, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.putString(CommonIdDef.SAVE_KEY_ORDER, o.toString());
        editor.commit();
    }

    private final static String DEFAULT_CATEORY_FILE_ORDER_STRING = FileOrder.date.toString();
    public static FileOrder loadCateorySaved(Context mActivity)
    {
        SharedPreferences sp = mActivity.getSharedPreferences(CommonIdDef.SAVE_KEY_PREFERENCE, Context.MODE_PRIVATE);
        FileOrder mOrder = FileOrder.valueOf(sp.getString(CommonIdDef.SAVE_KEY_CATEORY_ORDER, DEFAULT_CATEORY_FILE_ORDER_STRING));
        return mOrder;
    }
    public static void saveCateoryOrder(Context mActivity,FileOrder o)
    {
        SharedPreferences sp = mActivity.getSharedPreferences(CommonIdDef.SAVE_KEY_PREFERENCE, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.putString(CommonIdDef.SAVE_KEY_CATEORY_ORDER, o.toString());
        editor.commit();
    }

    static String mCommonPath = null;
    public final static String BroadcastActionScan = "com.aliyunos.filemanager.ActionScan";
    public static void StartDeleteMediaFile()
    {
        mCommonPath = null;
    }
    public static void DeleteMediaFile(File mFile)
    {
        String path = null;
        if(mFile.isFile())
        {
            path = mFile.getParent();
        }
        else
            path = mFile.getParentFile().getPath();//Need scan parent dir when delete directory
        String [] patharray ={path,mCommonPath};
        mCommonPath = CalculateCommonPath(patharray);
    }
    public static void EndDeleteMediaFile(Context m,boolean Self)
    {
        if(mCommonPath != null)
        {
            Uri localUri = Uri.fromFile(new File(mCommonPath));
            Intent localIntent = new Intent(BroadcastActionScan, localUri );//"android.intent.action.MEDIA_MOUNTED"
            localIntent.putExtra(CommonIdDef.DELETE_BY_FILEMANAGER, Self);
            m.sendBroadcast(localIntent);

            MediaScannerConnection.scanFile(m, new String[] { mCommonPath }, null,null);
        }
    }
    public static String CalculateCommonPath(Object[] filename)
    {
        FileInfo[] mFileInfo = null;
        String[] mStringInfo = null;
        boolean isString = false;
        if(filename == null)
            return null;
        if(filename[0] instanceof FileInfo)
        {
            isString = true;
            mFileInfo = (FileInfo[])filename;
        }
        else
        {
            isString = false;
            mStringInfo = (String[])filename;
        }

        Log.v(TAG, "FileDeleteDialog CalculateCommonPath");
        String CommonPath;
        if(isString)
        {
            CommonPath = mFileInfo[0].GetFilePath();
        }
        else
            CommonPath = mStringInfo[0];

        Log.v(TAG, "FileDeleteDialog CommonPath:" +CommonPath);
        for(int index =1;index < filename.length;index++)
        {
            String path = null;
            if(isString)
                path = mFileInfo[index].GetFilePath();
            else
                path = mStringInfo[index];
            if(path ==null)
                continue;
            if(path.equalsIgnoreCase(CommonPath))
                continue;
            if(path.contains(CommonPath))
                continue;
            while((path != null)&&(CommonPath!=null))
            {
                Log.v(TAG, "FileDeleteDialog while");
                if(path.length() > CommonPath.length())
                {
                    path = GetUpPath(path);
                    Log.v(TAG, "FileDeleteDialog path:" +path);
                }
                else
                {
                    if(CommonPath.equalsIgnoreCase(path))
                    {
                        CommonPath = path;
                        break;
                    }
                    CommonPath = GetUpPath(CommonPath);
                    Log.v(TAG, "FileDeleteDialog CommonPath:" +CommonPath);
                }
            }

        }
        return CommonPath;
    }
    public static String GetUpPath(String path)
    {
        String retPath = path.substring(0, path.lastIndexOf(File.separator));
        return retPath;

    }
    public static long listDirFileNum(File from,long BaseNum)
    {
        if(from.isFile())
        {
            BaseNum++;
        }
        else if(from.isDirectory())
        {
            File[] files = from.listFiles();
            if(files != null && files.length > 0)
            {
                for(File f : files)
                {
                    if(f.isFile())
                    {
                        BaseNum++;
                    }
                    else if(f.isDirectory())
                    {
                        BaseNum = listDirFileNum(f, BaseNum);
                    }
                }
            }
        }
        return BaseNum;
    }
    public static Bitmap ResizeBitmap2fitsize(Bitmap in,int fitW,int fitH)
    {
        if((in == null)||(fitW < 1)||(fitH<1))
            return null;
        int width = in.getWidth();
        int height = in.getHeight();
        int newWidth = fitW;
        int newHeight = fitH;
        if((width < 1)||(height<1))
            return null;
        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;
        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);
        Bitmap newbm = Bitmap.createBitmap(in, 0, 0, width, height, matrix,
                true);
        return newbm;
    }
    public static Bitmap ResizeBitmap2fitDrawable(Context m,Bitmap in)
    {
        int w,h;
        int dp = m.getResources().getInteger(R.integer.ListdrawableWidth);
        w = (int)AndroidHelper.convertDpToPixel(m, dp);
        h = w;
        return ResizeBitmap2fitsize(in,w,h);
    }
    public static Drawable showUninstallAPKIcon(String apkPath, Context m) {
        String PATH_PackageParser = "android.content.pm.PackageParser";
        String PATH_AssetManager = "android.content.res.AssetManager";
        try {

            Class pkgParserCls = Class.forName(PATH_PackageParser);
            Class[] typeArgs = new Class[1];
            typeArgs[0] = String.class;
            Constructor pkgParserCt = pkgParserCls.getConstructor(typeArgs);
            Object[] valueArgs = new Object[1];
            valueArgs[0] = apkPath;
            Object pkgParser = pkgParserCt.newInstance(valueArgs);
            Log.d("ANDROID_LAB", "pkgParser:" + pkgParser.toString());
            DisplayMetrics metrics = new DisplayMetrics();
            metrics.setToDefaults();
            // PackageParser.Package mPkgInfo = packageParser.parsePackage(new
            // File(apkPath), apkPath,
            // metrics, 0);
            typeArgs = new Class[4];
            typeArgs[0] = File.class;
            typeArgs[1] = String.class;
            typeArgs[2] = DisplayMetrics.class;
            typeArgs[3] = Integer.TYPE;
            Method pkgParser_parsePackageMtd = pkgParserCls.getDeclaredMethod("parsePackage",
                    typeArgs);
            valueArgs = new Object[4];
            valueArgs[0] = new File(apkPath);
            valueArgs[1] = apkPath;
            valueArgs[2] = metrics;
            valueArgs[3] = 0;
            Object pkgParserPkg = pkgParser_parsePackageMtd.invoke(pkgParser, valueArgs);
            // ApplicationInfo info = mPkgInfo.applicationInfo;
            Field appInfoFld = pkgParserPkg.getClass().getDeclaredField("applicationInfo");
            ApplicationInfo info = (ApplicationInfo) appInfoFld.get(pkgParserPkg);
            Log.d("ANDROID_LAB", "pkg:" + info.packageName + " uid=" + info.uid);
            // Resources pRes = getResources();
            // AssetManager assmgr = new AssetManager();
            // assmgr.addAssetPath(apkPath);
            // Resources res = new Resources(assmgr, pRes.getDisplayMetrics(),
            // pRes.getConfiguration());
            Class assetMagCls = Class.forName(PATH_AssetManager);
            Constructor assetMagCt = assetMagCls.getConstructor((Class[]) null);
            Object assetMag = assetMagCt.newInstance((Object[]) null);
            typeArgs = new Class[1];
            typeArgs[0] = String.class;
            Method assetMag_addAssetPathMtd = assetMagCls.getDeclaredMethod("addAssetPath",
                    typeArgs);
            valueArgs = new Object[1];
            valueArgs[0] = apkPath;
            assetMag_addAssetPathMtd.invoke(assetMag, valueArgs);
            Resources res = m.getResources();
            typeArgs = new Class[3];
            typeArgs[0] = assetMag.getClass();
            typeArgs[1] = res.getDisplayMetrics().getClass();
            typeArgs[2] = res.getConfiguration().getClass();
            Constructor resCt = Resources.class.getConstructor(typeArgs);
            valueArgs = new Object[3];
            valueArgs[0] = assetMag;
            valueArgs[1] = res.getDisplayMetrics();
            valueArgs[2] = res.getConfiguration();
            res = (Resources) resCt.newInstance(valueArgs);
            CharSequence label = null;
            if (info.labelRes != 0) {
                label = res.getText(info.labelRes);
            }
            // if (label == null) {
            // label = (info.nonLocalizedLabel != null) ? info.nonLocalizedLabel
            // : info.packageName;
            // }
            Log.d("ANDROID_LAB", "label=" + label);
            if (info.icon != 0) {
                Drawable icon = res.getDrawable(info.icon);
                //ImageView image = (ImageView) findViewById(R.id.apkIconBySodino);
                //image.setVisibility(View.VISIBLE);
                //image.setImageDrawable(icon);
                return icon;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
